package cn.tml.innermost.user.utils;

/**
 * @author yuech
 * @version 1.0
 * @description: TODO
 * @date 2022/11/18 13:21
 */

import com.aliyun.oss.OSSClient;
import org.apache.commons.lang.StringUtils;


import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.logging.Logger;

/**
 * @author welsir
 * @version 1.0
 * @description: TODO
 * @date 2022/9/20 20:31
 */
public class OssUtil {
    static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    static String accessKeyId = "LTAI5tRc7Kj2NDShzofCT6A9";
    static String accessKeySecret = "SVPcqecSSsCmwEfDTyJrIQWufeHePe";
    static String bucketName = "timemachinelab";

    public static void main(String[] args) {
        String path = "C:\\Users\\yuech\\Desktop\\周杰伦 - 爱情废柴.mp3";
        File file = new File(path);
        String FileName = "qwerqwe";
//        System.out.println(SaveToOss(file, FileName));
    }


    public static String SaveToOss(InputStream inputStream, String FileName, String prefix) {
        System.out.println("进入updUserProfile方法");
        String ObjectName = prefix + ":" + FileName;
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, ObjectName, inputStream);
        long expiration = new Date().getTime() + 3600L * 1000 * 24 * 365 * 10;
        Date expirationDate = new Date(expiration);
        URL url = ossClient.generatePresignedUrl(bucketName, ObjectName, expirationDate);
        System.out.println("url.toString()="+url.toString());
        ossClient.shutdown();
        return url.toString();
    }

    //删除文件
    public static boolean DeleteOssFile(String Filedirectory) {
        String res = "T" + StringUtils.substringAfter(StringUtils.substringBefore(Filedirectory, "?"), "T");
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        boolean exist = ossClient.doesObjectExist(bucketName, res);
        if (!exist) {
            System.out.println("文件不存在");
            return false;
        }
        ossClient.deleteObject(bucketName, res);
        ossClient.shutdown();
        return true;
    }
}
